import {FamilyInfo, FamilyReportInfo, queryFamilyReportPage} from '@/services/family/api';
import {ProColumnType, ProTable} from '@ant-design/pro-components';
import {Button, Modal} from 'antd';
import to from 'await-to-js';
import {marked} from 'marked';
import {type FC, useState} from 'react';
import {getCurrentDateTimeString, htmlToPdf} from "@/common/util";

import './report-list-modal.scss';

type ReportGenerateModalProps = {
  modalVisible: boolean;
  onOpenChange: (open: boolean) => void;
  familyInfo: FamilyInfo | undefined;
};

// export interface ReportListReqParam {
//   familyId?: number;
//   page?: number;
//   size?: number;
// }

const ReportListModal: FC<ReportGenerateModalProps> = (props) => {
  const {modalVisible, onOpenChange, familyInfo} = props;
  const [detailModalVisible, setDetailModalVisible] = useState(false);
  const [currentReportInfo, setCurrentReportInfo] = useState<FamilyReportInfo | undefined>(undefined);

  const params = {
    page: 1,
    size: 10,
  };

  const handleShowReportInfo = (record: FamilyReportInfo) => {
    // Modal.confirm({
    //   title: (<div style={{padding: '12px 24px', backgroundColor: '#fff'}}>报告详情</div>),
    //   width: 1200,
    //   content: <p dangerouslySetInnerHTML={{ __html: marked(record.report) }}></p>,
    // });
    setCurrentReportInfo(record);
    setDetailModalVisible(true);
  };

  const columns: ProColumnType<FamilyReportInfo>[] = [
    {
      title: '报告ID',
      dataIndex: 'id',
      key: 'id',
    },
    {
      title: '聊天记录数',
      dataIndex: 'sessionCount',
      key: 'id',
    },
    {
      title: '生成时间',
      dataIndex: 'createTime',
      key: 'id',
    },
    {
      title: '操作',
      key: 'id',
      render(_text, record) {
        return (
          <>
            <Button size="small" type="primary" onClick={() => handleShowReportInfo(record)}>查看报告</Button>
          </>
        );
      },
    },
  ];

  if (!modalVisible) {
    return null;
  }

  return (
    <>
      <Modal
        title={`家庭【${familyInfo?.name}(${familyInfo?.code})】的报告列表`}
        open={modalVisible}
        onCancel={() => {
          onOpenChange(false);
        }}
        width={680}
        centered={true}
        style={{
          maxHeight: '90%',
          overflowY: 'auto',
        }}
        footer={null}
      >
        <ProTable
          toolBarRender={false}
          defaultSize="small"
          rowKey={'id'}
          columns={columns}
          // params 是需要自带的参数
          // 这个参数优先级更高，会覆盖查询表单的参数
          params={params}
          // 第一个参数 params 查询表单和 params 参数的结合
          // 第一个参数中一定会有 pageSize 和  current ，这两个参数是 antd 的规范
          request={async () => {
            // 这里需要返回一个 Promise,在返回之前你可以进行数据转化
            // 如果需要转化参数可以在这里进行修改
            const [err, baseResponse] = await to(queryFamilyReportPage(familyInfo?.id, 1, 100));
            if (err) {
              return {data: [], success: false};
            }
            return {data: baseResponse?.result?.records, success: baseResponse?.code === '0'};
          }}
          pagination={false}
          search={false}
          debounceTime={100}
        />
      </Modal>

      <Modal
        className="report-detail-modal"
        title={`报告详情`}
        width={1200}
        open={detailModalVisible}
        onCancel={() => {
          setDetailModalVisible(false);
        }}
        cancelText="关闭"
        okText="下载报告"
        onOk={() => {
          const filename = `${familyInfo?.name}(${familyInfo?.code})的家庭沟通分析报告-${getCurrentDateTimeString()}`;
          htmlToPdf(document.querySelector("#curr-report-content"), filename);
        }}
      >
        <>
          <div id="curr-report-content">
            <h2>{familyInfo?.name}({familyInfo?.code}) 家庭沟通分析报告</h2>
            <div>
              {currentReportInfo?.sessionStartTime ? <div>报告分析会话时间范围：{currentReportInfo?.sessionStartTime} ~ {currentReportInfo?.sessionEndTime}</div> : null}
              <div dangerouslySetInnerHTML={{__html: marked(currentReportInfo?.report || '')}}></div>
            </div>
          </div>
        </>
      </Modal>
    </>
  );
};

export default ReportListModal;
